from django_redis import get_redis_connection
from . import meiduo_json
# 合并购物车
def merge_cart_cookie_to_redis(request,response):
    # 读取cookie
    cart_str = request.COOKIES.get("cart")
    user = request.user
    # 读取到数据
    if cart_str:
        cart_dict = meiduo_json.loads(cart_str)
        # 写入redis
        redis_cli = get_redis_connection("cart")
        redis_pl = redis_cli.pipeline()
        for sku_id,info in cart_dict.items():
            # 写hash
            redis_pl.hincrby("cart_%d"%user.id,sku_id,info["count"])
            # 写set
            if info["selected"]:
                redis_pl.sadd("selected_%d"%user.id,sku_id)
            else:
                redis_pl.srem("selected_%d"%user.id,sku_id)
        redis_pl.execute()
    # 删除cookie中的购物车信息
    response.delete_cookie("cart")
    return response



